import React, { ReactNode, useEffect, useState } from 'react';
import classNames from 'classnames';
import styles from './css/chatInput.module.css';
import IconSend from '@/components/Icons/IconSend';
import IconFile from '@/components/Icons/IconFile';
import { IChatDialogueMessageSchema } from '@/types/chat';
import { useAppDispatch } from '@/store';
import { addHistory, updateCurrentDialog } from '@/store/actions/chat';
import { v4 as uuidv4 } from 'uuid';
import { useAppSelector } from '@/store';

interface inputProps
  extends React.DetailedHTMLProps<React.TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement> {
  className?: string;
  extra?: ReactNode;
  errorMsg?: string;
  value?: string;
}

const userDialog = (text: string) => {
  const humanDialog: IChatDialogueMessageSchema = {
    uuid: uuidv4(),
    role: 'human',
    context: text,
  };
  return humanDialog;
};

const ChatInput: React.FC<inputProps> = ({ className, extra, errorMsg, value, onKeyDown, ...rest }) => {
  const dispatch = useAppDispatch();
  const [userInput, setUserInput] = useState('');
  const { currentDialog } = useAppSelector((state) => state.chat);

  // Focus事件监听
  useEffect(() => {
    const outerDiv = document.getElementById('areaApp');
    const textArea = document.getElementById('text') as HTMLDivElement;

    // 为 div 添加点击事件监听器
    outerDiv?.addEventListener('click', () => {
      textArea?.focus();
      // 改变 div 的边框颜色
      outerDiv.classList.add('border-sky-500');
    });

    // 监听 textarea 失去焦点的事件
    textArea?.addEventListener('blur', () => {
      // 恢复 div 的原始边框颜色
      outerDiv?.classList.remove('border-sky-500');
    });

    // 清理事件监听器
    return () => {
      outerDiv?.removeEventListener('click', () => {});
      textArea?.removeEventListener('blur', () => {});
    };
  }, []);

  const handleInputChage = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setUserInput(event.target.value);
  };

  // 处理键盘按下事件
  const handleKeyDown = async (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (event.key === 'Enter') {
      if (event.shiftKey) {
        // event.preventDefault();
      } else {
        // Enter 按下
        event.preventDefault(); // 阻止默认行为，比如换行
        if (currentDialog) {
          dispatch(addHistory(currentDialog));
        }
        dispatch(addHistory(userDialog(userInput)));
        setUserInput('');
        const aiDialogID = uuidv4();
        dispatch(updateCurrentDialog(aiDialogID, userInput));

        // const newChatContext = { ...chatContext };
        // newChatContext.context.push(userChat);
        // newChatContext.context.push(botChat);
        // if (newChatContext.chatid === '' || newChatContext.chatid === undefined) {
        //   newChatContext.chatid = uuidv4();
        // }
        // if (newChatContext.title === '' || newChatContext.title === undefined) {
        //   newChatContext.title = textValue.substring(0, 10);
        // }
        // setChatContext(newChatContext);
        // // 重置输入框
        // setTextValue('');
        // // 发送请求
        // askChatGPT(textValue, setGptResponse);
        // dispatch(addDialogDetail(newChatContext));
        // if (!router.query.id) {
        //   router.push({ pathname: '/chat', query: { id: newChatContext.chatid } });
        // }
      }
    }
  };

  return (
    <div
      id="areaApp"
      className={classNames(
        'flex items-center w-2/5 mx-auto rounded-lg border hover:border-sky-500 bg-white px-1',
        className,
      )}
    >
      <IconFile />
      <textarea
        {...rest}
        id="text"
        className={classNames('w-full h-full mx-1 ', styles.text)}
        style={{ resize: 'none', outline: 'none', fontSize: '16px' }}
        rows={1}
        placeholder={'send you message'}
        value={userInput}
        onKeyDown={handleKeyDown}
        onChange={handleInputChage}
      />
      <IconSend />
    </div>
  );
};

export default ChatInput;
